package net.qiqbframework.eventhandling;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MultiEventHandlerInvoker implements EventMessageHandler {

    private final List<EventMessageHandler> delegates;

    public MultiEventHandlerInvoker(EventMessageHandler... delegates) {
        this(Arrays.asList(delegates));
    }

    public MultiEventHandlerInvoker(@Nonnull List<EventMessageHandler> delegates) {
        this.delegates = flatten(delegates);
    }

    private List<EventMessageHandler> flatten(List<EventMessageHandler> invokers) {
        List<EventMessageHandler> flattened = new ArrayList<>();
        for (EventMessageHandler invoker : invokers) {
            if (invoker instanceof MultiEventHandlerInvoker) {
                flattened.addAll(((MultiEventHandlerInvoker) invoker).delegates());
            } else {
                flattened.add(invoker);
            }
        }
        return flattened;
    }

    @Nonnull
    public List<EventMessageHandler> delegates() {
        return Collections.unmodifiableList(delegates);
    }



    @Override
    public Object handle(@Nonnull EventMessage<?> message) throws Exception {
        for (EventMessageHandler i : delegates) {
            i.handle(message);
        }
        return null;
    }

}
